package cn.tedu.charging.cost.repository;

import cn.tedu.charging.common.enums.CostRuleEnum;
import cn.tedu.charging.cost.mapper.CostRuleMapper;
import cn.tedu.charging.common.pojo.po.ChargingCostRulePO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

@Repository
@Slf4j
public class CostRuleRepository extends ServiceImpl<CostRuleMapper, ChargingCostRulePO> {
    @Autowired
    private CostRuleMapper costRuleMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    public ChargingCostRulePO getCostRule(Integer stationId, Integer gunType, Integer hour) {
        //在redis存储的String类型的key值 拼接月数据 value就是po
        String ruleKey="charging:cost:rule:"+stationId+":"+gunType+":"+CostRuleEnum.getRuleName(hour);
        log.info("计价规则缓存key值:{}",ruleKey);
        ValueOperations<String, ChargingCostRulePO> opsForValue = redisTemplate.opsForValue();
        //1.读取缓存
        ChargingCostRulePO po = opsForValue.get(ruleKey);
        //2.判断缓存是否命中
        if(po!=null){
            log.info("缓存命中,数据:{}",po);
            return po;
        }else{
            //3.没有命中查询数据库 同时存放缓存
            log.info("缓存未命中,查询数据库");
            //select * from charging_cost_rule where station_id=? and gun_type=? and startTime<=hour and endTime>hour;
            QueryWrapper<ChargingCostRulePO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("station_id",stationId);
            queryWrapper.eq("gun_type",gunType);
            queryWrapper.le("start_time",hour);
            queryWrapper.gt("end_time",hour);
            po = costRuleMapper.selectOne(queryWrapper);
            if (po==null){
                throw new RuntimeException("没有找到对应规则");
            }else{
                opsForValue.set(ruleKey,po);
            }
        }
        return po;
    }
}
